package com.neusoft.neuiotms.dcom.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.model.InspectionRuleProjectItem;
import com.neusoft.neuiotms.dcom.model.QInspectionRuleProjectItem;
import com.neusoft.neuiotms.dcom.repository.CustomizedInspectionRuleProjectItemRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedInspectionRuleProjectItemRepositoryImpl extends AbstractRepository
        implements CustomizedInspectionRuleProjectItemRepository {

    @Override
    public List<InspectionRuleProjectItem> index(final Searchable searchable) {
        final QInspectionRuleProjectItem qInspectionRuleProjectItem =
                QInspectionRuleProjectItem.inspectionRuleProjectItem;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<InspectionRuleProjectItem> query = this.query().selectFrom(qInspectionRuleProjectItem);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<InspectionRuleProjectItem> page(final Searchable searchable, final Pageable pageable) {
        final QInspectionRuleProjectItem qInspectionRuleProjectItem =
                QInspectionRuleProjectItem.inspectionRuleProjectItem;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<InspectionRuleProjectItem> query = this.query().selectFrom(qInspectionRuleProjectItem);
        query.where(where);
        return super.search(query, pageable);
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QInspectionRuleProjectItem qInspectionRuleProjectItemProjectItem =
                QInspectionRuleProjectItem.inspectionRuleProjectItem;

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.and(super.containsStr(qInspectionRuleProjectItemProjectItem.name, searchable, "name"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("type"))) {
            where.and(super.containsStr(qInspectionRuleProjectItemProjectItem.type, searchable, "type"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("valueType"))) {
            where.and(super.containsStr(qInspectionRuleProjectItemProjectItem.valueType, searchable, "valueType"));
        }
        return where;
    }

    @Override
    protected Class<?> getModelClass() {
        return InspectionRuleProjectItem.class;
    }

}
